package com.hnas.eCard.service.impl;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hnas.account.dao.AccountDAO;
import com.hnas.account.orm.Account;
import com.hnas.api.domain.RouteFinalValue;
import com.hnas.api.dto.DTOResult;
import com.hnas.api.server.PostConnServer;
import com.hnas.api.util.CommonUtil;
import com.hnas.api.util.StringUtil;
import com.hnas.common.outdto.GetBalanceForm;
import com.hnas.common.util.CommonUtils;
import com.hnas.common.util.PostConnServerUtils;
import com.hnas.common.util.ResultCode;
import com.hnas.core.util.DateUtil;
import com.hnas.eCard.dao.AccECardDAO;
import com.hnas.eCard.dao.CardOptLogDAO;
import com.hnas.eCard.dao.CardTrailDAO;
import com.hnas.eCard.dao.ECardShareCodeDao;
import com.hnas.eCard.domain.BusinessType;
import com.hnas.eCard.domain.CardMarkConstant;
import com.hnas.eCard.domain.CardTrailStatus;
import com.hnas.eCard.domain.ECardCommonFinalValue;
import com.hnas.eCard.domain.ECardStatus;
import com.hnas.eCard.domain.ReturnECardMapper;
import com.hnas.eCard.domain.SendSMSThread;
import com.hnas.eCard.orm.AccECard;
import com.hnas.eCard.orm.CardOptLog;
import com.hnas.eCard.orm.CardTrail;
import com.hnas.eCard.service.AccECardService;
import com.hnas.trade.dao.OrderDao;

@Component("accECardService")
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public class AccECardServiceImpl implements AccECardService {
	
	@Value("#{component.channel_qrcode_str}")
	private String channelQrcodeStr;
	@Value("#{component.SMS_BDT_SENDCARD}")
	private String SMS_BDT_SENDCARD;
	@Value("#{component.SMS_BDT_RECEIVE_CARD_STATUS}")
	private String SMS_BDT_RECEIVE_CARD_STATUS;
	
	private static Log log = LogFactory.getLog(AccECardServiceImpl.class);
	
	@Autowired
	private AccECardDAO accECardDAO;
	
	@Autowired
	private CardTrailDAO cardTrailDAO;
	
	@Autowired
	private CardOptLogDAO cardOptLogDAO;
	
	@Autowired
	private AccountDAO accountDAO;
	
	@Autowired
	private OrderDao orderDao;
	@Autowired
	private ECardShareCodeDao eCardShareCodeDao;
	@Autowired
	private PostConnServerUtils postConnServerUtils;
	
	@Autowired
	private PostConnServer postConnServer;
	
	@Value("#{component['subCode']}") // 发卡类型
	private String subCode;
	@Value("#{component['merchant_id']}")
	private String merchantId;
	
	@Override
	public List<AccECard> findByECard(AccECard vo) {
		return accECardDAO.findByECardSql(vo);
	}

	@Override
	public List<AccECard> searchECard(AccECard vo) {
		return accECardDAO.findByECardSql(vo);
	}
	
	@Override
	public JSONObject findECardsByStatus(String accId, String searchStatus, Integer pageNo, Integer pageSize) throws Exception {
		JSONObject result = new JSONObject();
		List<AccECard> list = accECardDAO.findECardsByStatus(accId, searchStatus, pageNo, pageSize);
		if(null != list && list.size() > 0){
			JSONArray array = new JSONArray();
			JSONObject temp = null;
//			GetBalanceForm getBalanceForm = null;
			for(AccECard eCard : list){
				//查询可用的卡
//				if("03".equals(postConnServerUtils.getCardInfo(eCard.getCardNo()).getString("CARD_STAT"))){
					temp = new JSONObject();
//					getBalanceForm = new GetBalanceForm();
//					getBalanceForm.setCardNo(eCard.getCardNo());
//					getBalanceForm.setSubCode(subCode);
					temp.put(ECardCommonFinalValue.card_no, eCard.getCardNo());
					temp.put(ECardCommonFinalValue.card_mark, eCard.getCardMark());
					temp.put(ECardCommonFinalValue.status, ReturnECardMapper.getReturnECardStatus(searchStatus, eCard.getStatus()));
					temp.put(ECardCommonFinalValue.face_value, eCard.getFaceValue());
					temp.put(ECardCommonFinalValue.expiry_date, eCard.getExpiryDate());
//					temp.put(ECardCommonFinalValue.balance, postConnServerUtils.getBalance(getBalanceForm));
					temp.put(ECardCommonFinalValue.balance, "0");
					array.add(temp);
//				}
			}
			result.put(ECardCommonFinalValue.ecard_list, array);
		}
		return result;
	}
	
	@Override
	public AccECard saveOrUpdate(AccECard vo) throws Exception {
		return accECardDAO.saveOrUpdate(vo);
	}

	@Override
	public DTOResult sendECard(DTOResult dtoResult, JSONObject jo) throws Exception {
		JSONObject resultData = new JSONObject();
		resultData.put(ECardCommonFinalValue.opt_status, ECardCommonFinalValue.OPT_FAIL);
		String sendPhoneNo = CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.send_phone_no));
		String sendName = CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.send_name));
		AccECard searchAccECard = new AccECard();
		searchAccECard.setAccId(jo.getString(ECardCommonFinalValue.acc_id));
		searchAccECard.setCardNo(jo.getString(ECardCommonFinalValue.card_no));
		searchAccECard.setIsDeleted(false);
		List<AccECard> list = this.accECardDAO.searchECardSql(searchAccECard, true);
		//检查账户和卡号是否存在
		if(null == list || list.size() < 1) {
			log.info("赠送电子卡:账户id和卡号查询结果为空");
			dtoResult.setResultCode(ResultCode.ERROR_193);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_193));
			dtoResult.setResultData(resultData.toString());
			return dtoResult;
		}
		AccECard accECard = list.get(0);
		//判断账户电子卡状态是否正常
		if(!ECardStatus.NORMAL.equals(accECard.getStatus())) {
			log.info("赠送电子卡:账户电子卡状态非正常");
			dtoResult.setResultCode(ResultCode.ERROR_194);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_194));
			dtoResult.setResultData(resultData.toString());
			return dtoResult;
		}
		
		// 查询当前卡余额
		GetBalanceForm getBalanceForm = new GetBalanceForm();
		getBalanceForm.setCardNo(jo.getString(ECardCommonFinalValue.card_no));
		getBalanceForm.setSubCode(subCode);
		String currentBalance = this.postConnServerUtils.getBalance(getBalanceForm);
		
		//保存卡转赠轨迹
		CardTrail cardTrail = new CardTrail();
		cardTrail.setId(CommonUtils.getUUID());
		cardTrail.setSendAccId(jo.getString(ECardCommonFinalValue.acc_id));
		cardTrail.setSendPhoneNo(jo.getString(ECardCommonFinalValue.send_phone_no));
		cardTrail.setSendName(jo.getString(ECardCommonFinalValue.send_name));
		cardTrail.setSendCardNo(jo.getString(ECardCommonFinalValue.card_no));
		cardTrail.setCurrentBalance(currentBalance);
		cardTrail.setSendMsg(jo.getString(ECardCommonFinalValue.send_msg));
		cardTrail.setReceivePhoneNo(jo.getString(ECardCommonFinalValue.receive_phone_no));
		cardTrail.setReceiveName(jo.getString(ECardCommonFinalValue.receive_name));
		cardTrail.setStatus(CardTrailStatus.RECEIVING_GIVING);
		cardTrail.setSort(ECardCommonFinalValue.SORT_HEAD);
		CardTrail cardTrailBack = this.cardTrailDAO.saveOrUpdate(cardTrail);
		//编辑账户与电子卡关系状态
		accECard.setStatus(ECardStatus.GIVING);
		this.accECardDAO.saveOrUpdate(accECard);
		//开始发送短信
		JSONObject sendSMSReq = new JSONObject();
		List<String> paramList = new ArrayList<String>();
//		String para1 = "您的朋友"+sendPhoneNo+"赠送给您1张“宝岛通电子卡”，请关注微信“宝岛通”公众服务号，登录微信虚拟卡平台，进行查收。如有疑问，请咨询客服";
		paramList.add((sendName==null?"":sendName)+(sendPhoneNo==null?"":sendPhoneNo));
		paramList.add(jo.getString(ECardCommonFinalValue.card_no));
		paramList.add("963001");
		paramList.add("");
//		paramList.add(channelQrcodeStr);
		sendSMSReq.put(ECardCommonFinalValue.smsNum, jo.getString(ECardCommonFinalValue.receive_phone_no));
		sendSMSReq.put(ECardCommonFinalValue.smsContentList, paramList);
		sendSMSReq.put(ECardCommonFinalValue.tempId, SMS_BDT_SENDCARD);
//		JSONObject sendSMSRes = postConnServerUtils.sendSMS(sendSMSReq);
//		String dealMsg = "赠送电子卡成功";
//		if(!sendSMSRes.getBoolean("result")) {
//			dealMsg += ",但是短信发送失败";
//		}
		SendSMSThread sendSMS = new SendSMSThread(sendSMSReq);
		Thread thread = new Thread(sendSMS);
		thread.start();
		
		//保存卡操作日志
		CardOptLog cardOptLog = new CardOptLog();
		cardOptLog.setId(CommonUtils.getUUID());
		cardOptLog.setAccId(jo.getString(ECardCommonFinalValue.acc_id));
		cardOptLog.setCardNo(jo.getString(ECardCommonFinalValue.card_no));
		cardOptLog.setReqParam("赠送电子卡信息：" + jo.toJSONString() + " , 保存的卡轨迹信息：" + cardTrailBack.toString() + " , 发送短信参数：" + sendSMSReq.toJSONString());
//		cardOptLog.setReturnResult("发送短信结果返回：" + sendSMSRes.toJSONString());
		cardOptLog.setDealStatus(0);
		cardOptLog.setDealMsg("赠送电子卡成功");
		cardOptLog.setBusinessType(BusinessType.sendECard);
		cardOptLog.setRemark(BusinessType.getBusinessTypeString(BusinessType.sendECard));
		this.cardOptLogDAO.saveOrUpdate(cardOptLog);
		dtoResult.setResultCode(ResultCode.SUCCESS);
    	dtoResult.setResultMsg("赠送电子卡成功");
    	resultData.put(ECardCommonFinalValue.opt_status, ECardCommonFinalValue.OPT_SUCCESS);
    	dtoResult.setResultData(resultData.toString());
		return dtoResult;
	}

	@Override
	public List<AccECard> searchECardByAccIdAndStatus(String accId, String status) {
		AccECard vo = new AccECard();
		vo.setAccId(accId);
		vo.setStatus(status);
		return this.findByECard(vo);
	}

	@Override
	public DTOResult receiveOrRefuseECard(DTOResult dtoResult, JSONObject jo) throws Exception {
		String receiveType = jo.getString(ECardCommonFinalValue.receive_type);
		JSONObject resultData = new JSONObject();
		resultData.put(ECardCommonFinalValue.receive_type, receiveType);
		resultData.put(ECardCommonFinalValue.opt_status, ECardCommonFinalValue.OPT_FAIL);
		String cardNo = CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.card_no));
		String accId = CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.acc_id));
		//通过收卡人账户获取手机号码
		Account acc = this.accountDAO.findById(accId);
		String phoneNo = acc.getPhoneNo();
		if(null == acc || StringUtil.isEmpty(phoneNo)) {
			log.info("领取或拒绝电子卡:收卡人账户id查询账户信息结果为空");
			dtoResult.setResultCode(ResultCode.ERROR_198);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_198));
			dtoResult.setResultData(resultData.toString());
			return dtoResult;
		}
		//通过收卡人手机号码和卡号查询等待接收的卡轨迹
		CardTrail searchCardTrail = new CardTrail();
		searchCardTrail.setReceivePhoneNo(phoneNo);
		searchCardTrail.setSendCardNo(cardNo);
		searchCardTrail.setIsDeleted(false);
		searchCardTrail.setStatus(CardTrailStatus.RECEIVING_GIVING);
		List<CardTrail> cardTrailList = this.cardTrailDAO.searchCardTrailSql(searchCardTrail);
		//检查是否存在等待接收的电子卡
		if(null == cardTrailList || cardTrailList.size() < 1) {
			log.info("领取或拒绝电子卡:通过收卡人手机号码和卡号查询等待接收的电子卡结果为空");
			dtoResult.setResultCode(ResultCode.ERROR_199);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_199));
			dtoResult.setResultData(resultData.toString());
			return dtoResult;
		}
		//等待接收的电子卡数量不等于1
		if(1 != cardTrailList.size()) {
			log.info("领取或拒绝电子卡:等待接收的电子卡数量不等于1");
			dtoResult.setResultCode(ResultCode.ERROR_200);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_200));
			dtoResult.setResultData(resultData.toString());
			return dtoResult;
		}
		CardTrail cardTrail = cardTrailList.get(0);
		if(ECardCommonFinalValue.SALE_FOR_OTHER.equals(String.valueOf(cardTrail.getCreateType()))) {
			//保存卡操作日志
			CardOptLog cardOptLog = new CardOptLog();
			cardOptLog.setId(CommonUtils.getUUID());
			cardOptLog.setAccId(jo.getString(ECardCommonFinalValue.acc_id));
			cardOptLog.setCardNo(jo.getString(ECardCommonFinalValue.card_no));
			cardOptLog.setReqParam("领取或拒绝电子卡信息：" + jo.toJSONString());
			cardOptLog.setDealStatus(0);
			cardOptLog.setBusinessType(BusinessType.receiveOrRefuseECard);
			cardOptLog.setRemark(BusinessType.getBusinessTypeString(BusinessType.receiveOrRefuseECard));
			
			//先插入一条
			AccECard vo = new AccECard(CommonUtils.getUUID(), accId, cardNo, Long.valueOf(cardTrail.getCurrentBalance()), null, CardMarkConstant.ELEC_CARD, null, ECardStatus.NORMAL, "购卡给他人的卡");
			vo.setIsDeleted(false);
			vo.setCreator(accId);
			vo.setUpdater(accId);
			this.cardTrailDAO.receiveSaleForOtherECard(accId,cardTrail);
			this.accECardDAO.saveOrUpdate(vo);
//			this.cardTrailDAO.receiveECardUpdate(vo.getId(),cardTrail.getId(),accId);
			cardOptLog.setDealMsg("领取电子卡成功");
			dtoResult.setResultMsg("领取电子卡成功");
//			this.cardOptLogDAO.saveOrUpdate(cardOptLog);
			sendReceiveCardWxMessage(cardTrail,"领取成功");
		}else {
			//电子卡表是否存在转增中的卡
			AccECard searchAccECard = new AccECard();
			searchAccECard.setCardNo(jo.getString(ECardCommonFinalValue.card_no));
			searchAccECard.setStatus(ECardStatus.GIVING);
			searchAccECard.setIsDeleted(false);
			List<AccECard> list = this.accECardDAO.searchECardSql(searchAccECard, true);
			if(null == list || list.size() < 1) {
				log.info("领取或拒绝电子卡:电子卡转赠中不存在该卡号");
				dtoResult.setResultCode(ResultCode.ERROR_201);
				dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_201));
				dtoResult.setResultData(resultData.toString());
				return dtoResult;
			}
			AccECard accECard = list.get(0);
			
			
			//保存卡操作日志
			CardOptLog cardOptLog = new CardOptLog();
			cardOptLog.setId(CommonUtils.getUUID());
			cardOptLog.setAccId(jo.getString(ECardCommonFinalValue.acc_id));
			cardOptLog.setCardNo(jo.getString(ECardCommonFinalValue.card_no));
			cardOptLog.setReqParam("领取或拒绝电子卡信息：" + jo.toJSONString());
			cardOptLog.setDealStatus(0);
			cardOptLog.setBusinessType(BusinessType.receiveOrRefuseECard);
			cardOptLog.setRemark(BusinessType.getBusinessTypeString(BusinessType.receiveOrRefuseECard));
			//领取电子卡
			if(ECardCommonFinalValue.RECEIVE_TYPE.equals(receiveType)) {
				this.cardTrailDAO.receiveECardUpdate(accECard.getId(),cardTrail.getId(),accId);
				cardOptLog.setDealMsg("领取电子卡成功");
				dtoResult.setResultMsg("领取电子卡成功");
				sendReceiveCardWxMessage(cardTrail,"领取成功");
			}else if (ECardCommonFinalValue.REFUSE_TYPE.equals(receiveType)) {
				this.cardTrailDAO.refuseECardUpdate(accECard.getId(),cardTrail.getId(),accId);
				cardOptLog.setDealMsg("拒绝电子卡成功");
				dtoResult.setResultMsg("拒绝电子卡成功");
				sendReceiveCardWxMessage(cardTrail,"拒绝领取");
			}
			this.cardOptLogDAO.saveOrUpdate(cardOptLog);
		}
		dtoResult.setResultCode(ResultCode.SUCCESS);
    	resultData.put(ECardCommonFinalValue.opt_status, ECardCommonFinalValue.OPT_SUCCESS);
    	dtoResult.setResultData(resultData.toString());
		return dtoResult;
	}

	@Override
	public DTOResult backCardApply(DTOResult dtoResult, JSONObject jo) throws Exception {
		JSONObject resultData = new JSONObject();
//		resultData.put(ECardCommonFinalValue.opt_status, ECardCommonFinalValue.OPT_FAIL);
		String cardNo = jo.getString(ECardCommonFinalValue.card_no);
		String accId = jo.getString(ECardCommonFinalValue.acc_id);
		//通过收卡人账户获取手机号码
		Account acc = this.accountDAO.findById(accId);
		String phoneNo = acc.getPhoneNo();
		if(null == acc || StringUtil.isEmpty(phoneNo)) {
			log.info("电子卡退卡申请:查询账户手机号码信息结果为空");
			dtoResult.setResultCode(ResultCode.ERROR_205);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_205));
			dtoResult.setResultData(resultData.toString());
			return dtoResult;
		}
				
		AccECard searchAccECard = new AccECard();
		searchAccECard.setAccId(accId);
		searchAccECard.setCardNo(cardNo);
		searchAccECard.setIsDeleted(false);
		List<AccECard> list = this.accECardDAO.searchECardSql(searchAccECard, true);
		//检查账户和卡号是否存在
		if(null == list || list.size() < 1) {
			log.info("电子卡退卡申请:账户id和卡号查询电子卡结果为空");
			dtoResult.setResultCode(ResultCode.ERROR_193);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_193));
//			dtoResult.setResultData(resultData.toString());
			return dtoResult;
		}
		AccECard accECard = list.get(0);
		//只有电子卡才能申请退卡
		if(!CardMarkConstant.ELEC_CARD.equals(accECard.getCardMark())) {
			log.info("电子卡退卡申请:卡标记非电子卡");
			dtoResult.setResultCode(ResultCode.ERROR_206);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_206));
//			dtoResult.setResultData(resultData.toString());
			return dtoResult;
		}
		//电子卡状态为正常或退卡中才能申请退卡
		if(!ECardStatus.NORMAL.equals(accECard.getStatus()) && !ECardStatus.BACK_CARDING.equals(accECard.getStatus())) {
			log.info("电子卡退卡申请:电子卡状态不是正常或退卡中");
			dtoResult.setResultCode(ResultCode.ERROR_207);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_207));
//			dtoResult.setResultData(resultData.toString());
			return dtoResult;
		}
		//检查电子卡是否有卡转增中或已转赠记录
		String someStatus = CardTrailStatus.RECEIVING_GIVING + "," + CardTrailStatus.CONFIRM_RECEIVE_GIVE;
		List<CardTrail> cardTrailList = this.cardTrailDAO.findCardTrailsByCardNoAndSomeStatus(cardNo, someStatus, null);
		if(null != cardTrailList && cardTrailList.size() > 0) {
			log.info("电子卡退卡申请:电子卡有已转增或转增中记录");
			dtoResult.setResultCode(ResultCode.ERROR_208);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_208));
//			dtoResult.setResultData(resultData.toString());
			return dtoResult;
		}
		//检查电子卡是否有交易记录(除掉购卡记录)
		int orderCount = this.orderDao.getOrderCountByCardNo(cardNo);
		if(orderCount > 0) {
			log.info("电子卡退卡申请:电子卡存在消费记录");
			dtoResult.setResultCode(ResultCode.ERROR_209);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_209));
//			dtoResult.setResultData(resultData.toString());
			return dtoResult;
		}
		
		//调用接口获取退卡码
		JSONObject applyReq = new JSONObject();
		applyReq.put(ECardCommonFinalValue.cardNo, cardNo);
		applyReq.put(ECardCommonFinalValue.phoneNo, phoneNo);
		applyReq.put(ECardCommonFinalValue.merchantId, merchantId);
		JSONObject applyRes = this.postConnServer.getResultData(applyReq, RouteFinalValue.APP_ECARD_BackCardApply, JSONObject.class);
		if(null == applyRes) {
			log.info("电子卡退卡申请:调用电子卡退卡申请接口结果异常");
			dtoResult.setResultCode(ResultCode.ERROR_210);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_210));
			return dtoResult;
		}
		String refundCode = applyRes.getString(ECardCommonFinalValue.refundCode);
		if(StringUtil.isEmpty(refundCode)) {
			log.info("电子卡退卡申请:调用电子卡退卡申请接口结果为空");
			dtoResult.setResultCode(ResultCode.ERROR_211);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_211));
			return dtoResult;
		}
		
		//编辑账户与电子卡关系状态（退卡中）
		accECard.setStatus(ECardStatus.BACK_CARDING);
		this.accECardDAO.saveOrUpdate(accECard);

		//保存卡操作日志
		CardOptLog cardOptLog = new CardOptLog();
		cardOptLog.setId(CommonUtils.getUUID());
		cardOptLog.setAccId(jo.getString(ECardCommonFinalValue.acc_id));
		cardOptLog.setCardNo(jo.getString(ECardCommonFinalValue.card_no));
		cardOptLog.setReqParam("电子卡退卡申请信息：" + jo.toJSONString() + " , 获取退卡码参数；" + applyReq.toString());
		cardOptLog.setReturnResult("获取退卡码结果返回：" + applyRes.toJSONString());
		cardOptLog.setDealStatus(0);
		cardOptLog.setDealMsg("电子卡退卡申请成功");
		cardOptLog.setBusinessType(BusinessType.backCardApply);
		cardOptLog.setRemark(BusinessType.getBusinessTypeString(BusinessType.backCardApply));
		this.cardOptLogDAO.saveOrUpdate(cardOptLog);
		dtoResult.setResultCode(ResultCode.SUCCESS);
    	dtoResult.setResultMsg("电子卡退卡申请成功");
    	resultData.put(ECardCommonFinalValue.refund_code, refundCode);
    	dtoResult.setResultData(resultData.toString());
		return dtoResult;
	}

	@Override
	public DTOResult checkCardSecretKey(DTOResult dtoResult, JSONObject jo) throws Exception {
		JSONObject resultData = new JSONObject();
		//检查实体卡号是否已经存在
		AccECard searchAccECard = new AccECard();
		searchAccECard.setCardNo(jo.getString(ECardCommonFinalValue.card_no));
		List<AccECard> list = this.accECardDAO.searchECardSql(searchAccECard, false);
		//检查账户和卡号是否存在
		if(null != list && list.size() > 0) {
			log.info("电子卡卡号秘钥校验:该实体卡已存在");
			dtoResult.setResultCode(ResultCode.ERROR_212);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_212));
			return dtoResult;
		}
		//调用接口校验卡号和秘钥
		JSONObject req = new JSONObject();
		req.put(ECardCommonFinalValue.cardNo, jo.getString(ECardCommonFinalValue.card_no));
		req.put(ECardCommonFinalValue.secretKey, jo.getString(ECardCommonFinalValue.secret_key));
		req.put(ECardCommonFinalValue.merchantId, merchantId);
		JSONObject res = this.postConnServer.getResultData(req, RouteFinalValue.APP_ECARD_CheckCardSecretKey, JSONObject.class);
		if(null == res) {
			log.info("电子卡卡号秘钥校验:调用电子卡卡号秘钥校验结果异常");
			dtoResult.setResultCode(ResultCode.ERROR_213);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_213));
			return dtoResult;
		}
		String checkStatus = res.getString(ECardCommonFinalValue.checkStatus);
		
		if(StringUtil.isEmpty(checkStatus)) {
			log.info("电子卡卡号秘钥校验:调用电子卡卡号秘钥校验结果为空");
			dtoResult.setResultCode(ResultCode.ERROR_214);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_214));
			return dtoResult;
		}
		
		String accId = jo.getString(ECardCommonFinalValue.acc_id);
		//保存卡操作日志
		CardOptLog cardOptLog = new CardOptLog();
		cardOptLog.setId(CommonUtils.getUUID());
		cardOptLog.setAccId(accId);
		cardOptLog.setCardNo(jo.getString(ECardCommonFinalValue.card_no));
		cardOptLog.setReqParam("电子卡卡号秘钥校验信息：" + jo.toJSONString() + " , 电子卡卡号秘钥验证参数；" + req.toString());
		cardOptLog.setReturnResult("电子卡卡号秘钥验证结果返回：" + res.toJSONString());
		cardOptLog.setBusinessType(BusinessType.checkCardSecretKey);
		cardOptLog.setRemark(BusinessType.getBusinessTypeString(BusinessType.checkCardSecretKey));
		if("1".equals(checkStatus)) {
			String balance = res.getString(ECardCommonFinalValue.balance);
			if(StringUtil.isEmpty(balance)) {
				balance = "0";
			}
			AccECard accECard = new AccECard();
			accECard.setId(CommonUtils.getUUID());
			accECard.setAccId(accId);
			accECard.setCardNo(jo.getString(ECardCommonFinalValue.card_no));
			accECard.setCardMark(CardMarkConstant.ENTITY_CARD);
			accECard.setFaceValue(Long.valueOf(balance));
			accECard.setIsDeleted(false);
			accECard.setCreateTime(DateUtil.dateTimeToString(new Date()));
			accECard.setCreator(accId);
			accECard.setRemark("实体卡开卡成功");
			accECard.setStatus(ECardStatus.NORMAL);
			accECard.setUpdater(accId);
			accECard.setUpdateTime(DateUtil.dateTimeToString(new Date()));
			this.accECardDAO.saveOrUpdate(accECard);
			cardOptLog.setDealStatus(0);
			cardOptLog.setDealMsg("电子卡卡号秘钥验证通过");
			dtoResult.setResultCode(ResultCode.SUCCESS);
			dtoResult.setResultMsg("电子卡卡号秘钥验证通过");
		}else if("0".equals(checkStatus)) {
			cardOptLog.setDealStatus(1);
			cardOptLog.setDealMsg("电子卡卡号秘钥验证不通过");
			dtoResult.setResultCode(ResultCode.FAIL);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_213));
		}
		
		this.cardOptLogDAO.saveOrUpdate(cardOptLog);
    	resultData.put(ECardCommonFinalValue.opt_status, checkStatus);
    	dtoResult.setResultData(resultData.toString());
		return dtoResult;
	}

	@Override
	public void updateECardStatus(String accId) throws Exception {
		AccECard vo = new AccECard();
		vo.setAccId(accId);
		vo.setStatus(ECardStatus.BACK_CARDING);//退卡中
		List<AccECard> cards = this.searchECard(vo);
		if(!CollectionUtils.isEmpty(cards)){
			//更新卡状态
			for(AccECard card : cards){
				//查询卡状态为非正常的卡
				if(!"03".equals(postConnServerUtils.getCardInfo(card.getCardNo()).getString("CARD_STAT"))){
					card.setStatus(ECardStatus.BACK_CARD);
					accECardDAO.saveOrUpdate(card);
				}
			}
		}
	}

	@Override
	public DTOResult cancelGiveECard(DTOResult dtoResult, JSONObject jo) throws Exception {
		JSONObject resultData = new JSONObject();
		String cardNo = CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.card_no));
		String accId = CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.acc_id));
		resultData.put(ECardCommonFinalValue.opt_status, ECardCommonFinalValue.OPT_FAIL);
		//通过收卡人账户获取手机号码
		Account acc = this.accountDAO.findById(accId);
		if(null == acc) {
			log.info("取消贈送电子卡:赠卡人账户id查询账户信息结果为空");
			dtoResult.setResultCode(ResultCode.ERROR_217);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_217));
			dtoResult.setResultData(resultData.toString());
			return dtoResult;
		}
		//锁卡轨迹表的行
		CardTrail queryCardTrail = new CardTrail();
		queryCardTrail.setSendAccId(accId);
		queryCardTrail.setSendCardNo(cardNo);
		queryCardTrail.setIsDeleted(false);
		queryCardTrail.setStatus(CardTrailStatus.RECEIVING_GIVING);
		List<CardTrail> cardTrailList = this.cardTrailDAO.searchCardTrailSql(queryCardTrail);
		//检查是否存在等待接收的电子卡
		if(null == cardTrailList || cardTrailList.size() < 1) {
			log.info("取消贈送电子卡:通过赠卡人id和卡号查询等待接收的电子卡结果为空");
			dtoResult.setResultCode(ResultCode.ERROR_218);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_218));
			dtoResult.setResultData(resultData.toString());
			return dtoResult;
		}
		//等待接收的电子卡数量不等于1
		if(1 != cardTrailList.size()) {
			log.info("取消贈送电子卡:等待接收的电子卡数量不等于1");
			dtoResult.setResultCode(ResultCode.ERROR_200);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_200));
			dtoResult.setResultData(resultData.toString());
			return dtoResult;
		}	
		//电子卡表是否存在转增中的卡
		AccECard searchAccECard = new AccECard();
		searchAccECard.setCardNo(jo.getString(ECardCommonFinalValue.card_no));
		searchAccECard.setStatus(ECardStatus.GIVING);
		searchAccECard.setIsDeleted(false);
		List<AccECard> list = this.accECardDAO.searchECardSql(searchAccECard, true);
		if(null == list || list.size() < 1) {
			log.info("领取或拒绝电子卡:电子卡转赠中不存在该卡号");
			dtoResult.setResultCode(ResultCode.ERROR_201);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_201));
			dtoResult.setResultData(resultData.toString());
			return dtoResult;
		}
		CardTrail cardTrail = cardTrailList.get(0);
		AccECard accECard = list.get(0);
		if(accECard == null) {
			log.info("取消贈送电子卡:无该电子卡的账户绑定记录");
			dtoResult.setResultCode(ResultCode.ERROR_219);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_219));
			dtoResult.setResultData(resultData.toString());
			return dtoResult;
		}
		//修改卡状态和卡轨迹状态
		this.cardTrailDAO.cancelGiveUpdate(accECard.getId(),cardTrail.getId());
		//保存卡操作日志
		CardOptLog cardOptLog = new CardOptLog();
		cardOptLog.setId(CommonUtils.getUUID());
		cardOptLog.setAccId(jo.getString(ECardCommonFinalValue.acc_id));
		cardOptLog.setCardNo(jo.getString(ECardCommonFinalValue.card_no));
		cardOptLog.setReqParam("取消赠送电子卡信息：" + jo.toJSONString());
		cardOptLog.setDealStatus(0);
		cardOptLog.setBusinessType(BusinessType.cancelGiveECard);
		cardOptLog.setRemark(BusinessType.getBusinessTypeString(BusinessType.cancelGiveECard));
		//取消赠送电子卡
		cardOptLog.setDealMsg("取消赠送电子卡成功");
		this.cardOptLogDAO.saveOrUpdate(cardOptLog);
		
		dtoResult.setResultMsg("取消赠送电子卡成功");
				
		dtoResult.setResultCode(ResultCode.SUCCESS);
		resultData.put(ECardCommonFinalValue.opt_status, ECardCommonFinalValue.OPT_SUCCESS);
		dtoResult.setResultData(resultData.toString());
		return dtoResult;
	}

	@Override
	public DTOResult shareReceiveECard(DTOResult dtoResult, JSONObject jo) throws Exception {
		JSONObject resultData = new JSONObject();
		resultData.put(ECardCommonFinalValue.opt_status, ECardCommonFinalValue.OPT_FAIL);
		String shareCode = CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.share_code));
		String accId = CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.acc_id));
		//通过收卡人账户获取手机号码
		Account acc = this.accountDAO.findById(accId);
		String phoneNo = acc.getPhoneNo();
		if(null == acc || StringUtil.isEmpty(phoneNo)) {
			log.info("领取或拒绝电子卡:收卡人账户id查询账户信息结果为空");
			dtoResult.setResultCode(ResultCode.ERROR_198);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_198));
			dtoResult.setResultData(resultData.toString());
			return dtoResult;
		}
		//自己不能领取自己分享的卡
		//通过收卡人手机号码和卡号查询等待接收的卡轨迹
		CardTrail searchCardTrail = new CardTrail();
		searchCardTrail.setIsDeleted(false);
		searchCardTrail.setShareCode(shareCode);
		searchCardTrail.setStatus(CardTrailStatus.RECEIVING_GIVING);
		List<CardTrail> cardTrailList = this.cardTrailDAO.searchCardTrailSql(searchCardTrail);
		//检查是否存在等待接收的电子卡
		if(null == cardTrailList || cardTrailList.size() < 1) {
			log.info("领取或拒绝电子卡:查询不到该卡的分享记录");
			dtoResult.setResultCode(ResultCode.ERROR_226);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_226));
			dtoResult.setResultData(resultData.toString());
			return dtoResult;
		}
		//等待接收的电子卡数量不等于1
		if(1 != cardTrailList.size()) {
			log.info("领取或拒绝电子卡:等待接收的电子卡数量不等于1");
			dtoResult.setResultCode(ResultCode.ERROR_200);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_200));
			dtoResult.setResultData(resultData.toString());
			return dtoResult;
		}
		CardTrail cardTrail = cardTrailList.get(0);
		if(acc.getId().equals(cardTrail.getSendAccId())) {
			dtoResult.setResultCode(ResultCode.SUCCESS);
	    	resultData.put(ECardCommonFinalValue.opt_status, ECardCommonFinalValue.OPT_UNABLE_SELF);
	    	dtoResult.setResultData(resultData.toString());
	    	return dtoResult;
		}
		cardTrail.setReceivePhoneNo(acc.getPhoneNo());
		cardTrail.setReceiveWxImage(CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.wx_image)));
		cardTrail.setReceiveWxName(CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.wx_name)));
		cardTrail.setReceiveName(CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.wx_name)));
		//保存卡操作日志
		CardOptLog cardOptLog = new CardOptLog();
		cardOptLog.setId(CommonUtils.getUUID());
		cardOptLog.setAccId(jo.getString(ECardCommonFinalValue.acc_id));
		cardOptLog.setCardNo(jo.getString(ECardCommonFinalValue.card_no));
		cardOptLog.setReqParam("领取或拒绝电子卡信息：" + jo.toJSONString());
		cardOptLog.setDealStatus(0);
		cardOptLog.setBusinessType(BusinessType.receiveOrRefuseECard);
		cardOptLog.setRemark(BusinessType.getBusinessTypeString(BusinessType.receiveOrRefuseECard));
		//先插入一条
		AccECard searchVO = new AccECard();
		searchVO.setCardNo(cardTrail.getSendCardNo());
		List<AccECard> list = this.accECardDAO.findByECardSql(searchVO);
		if(list == null || list.size() < 0) {
			log.info("领取电子卡:通过卡号查询等待接收的电子卡结果为空");
			dtoResult.setResultCode(ResultCode.ERROR_218);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.ERROR_218));
			dtoResult.setResultData(resultData.toString());
			return dtoResult;
		}
		AccECard vo = list.get(0);
		vo.setAccId(accId);
		vo.setStatus(ECardStatus.NORMAL);
		this.cardTrailDAO.shareReceiveECard(acc,cardTrail);
		this.accECardDAO.saveOrUpdate(vo);
		cardOptLog.setDealMsg("领取电子卡成功");
		dtoResult.setResultMsg("领取电子卡成功");
		sendReceiveCardWxMessage(cardTrail,"领取成功");
		dtoResult.setResultCode(ResultCode.SUCCESS);
    	resultData.put(ECardCommonFinalValue.opt_status, ECardCommonFinalValue.OPT_SUCCESS);
    	dtoResult.setResultData(resultData.toString());
		return dtoResult;
	}
	
	/**
	 * 发送微信消息
	 * @Title: sendWxMessage  
	 * @Description:  
	 * @param orderDto
	 * @throws
	 */
	private void sendReceiveCardWxMessage(CardTrail cardTrail,String status) {
		/*Account account = this.accountDAO.findById(cardTrail.getSendAccId());
		JSONObject remindData = new JSONObject();
		remindData.put("openIdStr", account.getOpenId());
		remindData.put("modelType", "1");
		remindData.put("cardNo", cardTrail.getSendCardNo());
		remindData.put("receivePhoneNo", cardTrail.getReceivePhoneNo());
		remindData.put("receiveStatus", status);
		remindData.put("operateTime", cardTrail.getUpdateTime());
		remindData.put("first", CommonConstants.FIRST_5);
		remindData.put("remark", CommonConstants.REMARK_1);
		ReceiveCardRemindThread remindTread = new ReceiveCardRemindThread(remindData);
		Thread thread = new Thread(remindTread);
		thread.start();*/
		JSONObject sendSMSReq = new JSONObject();
		List<String> paramList = new ArrayList<String>();
		paramList.add(cardTrail.getSendCardNo());
		String receiveName = cardTrail.getReceiveWxName()==null?"":cardTrail.getReceiveWxName();
		String decodeName = "";
		try {
			if(StringUtil.isEmpty(receiveName)) {
				decodeName = (cardTrail.getReceiveName()==null?"":cardTrail.getReceiveName());
			}else {
				decodeName = URLDecoder.decode(receiveName,"utf-8");
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String receivePhoneNo = cardTrail.getReceivePhoneNo()==null?"":cardTrail.getReceivePhoneNo();
		paramList.add(decodeName+receivePhoneNo);
		paramList.add(status);
		paramList.add("963001");
		sendSMSReq.put(ECardCommonFinalValue.smsNum, cardTrail.getSendPhoneNo());
		sendSMSReq.put(ECardCommonFinalValue.smsContentList, paramList);
		sendSMSReq.put(ECardCommonFinalValue.tempId, SMS_BDT_RECEIVE_CARD_STATUS);
		SendSMSThread sendSMS = new SendSMSThread(sendSMSReq);
		Thread thread = new Thread(sendSMS);
		thread.start();
	}

	@Override
	public int unbindECard(String accId, String cardNo) {
		return this.accECardDAO.unbindECard(accId,cardNo);
	}

}
